package com.tanhua.manage.service;

import cn.hutool.core.date.DateUtil;
import com.tanhua.manage.domain.AnalysisByDay;
import com.tanhua.manage.mapper.AnalysisByDayMapper;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.utils.ComputeUtil;
import com.tanhua.manage.vo.AnalysisSummaryVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AnalysisService {
    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    private LogMapper logMapper;

    /**
     * 首页的概要统计
     * @return
     */
    public AnalysisSummaryVo summary(){
        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        Date todayDate = new Date();
        //1.查询累计用户数
        Long cumulativeUsers = analysisByDayMapper.totalUserCount();
        vo.setCumulativeUsers(cumulativeUsers);
        //2.过去7天日期、30天日期
        String last7Date = DateUtil.offsetDay(todayDate,-7).toDateStr();
        String last30Date = DateUtil.offsetDay(todayDate,-30).toDateStr();
        //2.1 活跃用户数
        //过去7天活跃用户
        Long activePassWeek = logMapper.countActiveUserAfterDate(last7Date);
        vo.setActivePassWeek(activePassWeek);
        //过去7天活跃用户
        Long activePassMonth = logMapper.countActiveUserAfterDate(last30Date);
        vo.setActivePassMonth(activePassMonth);
        //3.获取今天日期
        String today = DateUtil.today();
        //昨天
        String yesterday = DateUtil.yesterday().toDateStr();
        //今天数据
        AnalysisByDay todayData = analysisByDayMapper.findByDate(today);
        vo.setLoginTimesToday(todayData.getNumLogin());
        vo.setNewUsersToday(todayData.getNumRegistered());
        vo.setActiveUsersToday(todayData.getNumActive());

        //昨天数据
        AnalysisByDay yesterdayData = analysisByDayMapper.findByDate(yesterday);

        //计算3个环比
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(todayData.getNumRegistered(),yesterdayData.getNumRegistered()));
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(todayData.getNumLogin(),yesterdayData.getNumLogin()));
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(todayData.getNumActive(),yesterdayData.getNumActive()));

        //构建vo，返回
        return vo;
    }
}
